package com.bolingcavalry.crm.security.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class SecurityUtils {
    /**
     * 获取当前登录用户名
     * @return
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName();
        }
        return null;
        // 或抛出异常
    }

    /**
     * 获取当前登录用户的角色
     * @return
     */
    public static String getCurrentUserRole() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getAuthorities().iterator().next().getAuthority();
        }
        return null;
    }

    /**
     * 获取当前登录用户的所有角色
     * @return 角色列表
     */
    public static List<String> getCurrentUserRoles() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getAuthorities().stream()
                    .map(grantedAuthority -> {
                        String role = grantedAuthority.getAuthority();
                        // 去掉 ROLE_ 前缀
                        return role.startsWith("ROLE_") ? role.substring(5) : role;
                    })
                    .collect(Collectors.toList());
        }
        return List.of();
    }

}
